use axum::{extract::State, Json};
use serde::{Deserialize, Serialize};
use sqlx::{Pool, Sqlite};

use crate::jwt::{Claims, HttpError};

#[derive(Deserialize, sqlx::FromRow)]
pub struct User {
    email: String,
    password: String,
}

pub type LoginRequest = User;

#[derive(Serialize)]
pub struct LoginResponse {
    token: String,
}

pub async fn login_handler(
    State(pool): State<Pool<Sqlite>>,
    Json(login): Json<LoginRequest>,
) -> Result<Json<LoginResponse>, HttpError> {
    let email = login.email;
    let password = login.password;
    // This is just for example. You should encrypt the storage password.
    if let Ok(user) = sqlx::query_as::<_, User>("select * from users where email = ?")
        .bind(&email)
        .fetch_one(&pool)
        .await
    {
        if password == user.password {
            let claims = Claims::new(1, &user.email);
            Ok(Json(LoginResponse {
                token: claims.get_jwt(),
            }))
        } else {
            Err(HttpError::Login)
        }
    } else {
        Err(HttpError::Login)
    }
}
